#include <iostream>
#include <spdlog/sinks/basic_file_sink.h>
#include <spdlog/spdlog.h>
#include <thread>

#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

std::shared_ptr<spdlog::logger> logger;

void handle_sigterm(int sig)
{
    printf("Received SIGTERM, cleaning up and exiting...\n");
    if (logger != nullptr)
    {
        logger->info("Exit with signal.");
        logger->flush();
    }
    exit(0);
}

int main()
{
    struct sigaction sa;
    sa.sa_handler = handle_sigterm;
    sigemptyset(&sa.sa_mask);
    sa.sa_flags = 0;
    if (sigaction(SIGTERM, &sa, NULL) == -1)
    {
        perror("sigaction");
        exit(1);
    }

    // 初始化 spdlog 日志
    logger = spdlog::basic_logger_st("child_process", "./log/child/example_program.log");
    logger->info("Hello, world!");
    logger->info("This is an example program.");
    for (int i = 0; i < 10; i++)
    {
        std::this_thread::sleep_for(std::chrono::seconds(1));
        logger->info("Pass 1 seconds.");
    }
    logger->info("This program will exit in 10 seconds.");
    logger->flush();
    return 0;
}